package com.basic.app.exception;

import com.basic.app.response.AppResponse;
import com.basic.app.response.AppResponseCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * APP的全局异常处理器
 * @author Administrator
 */
@RestControllerAdvice
public class AppExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(BizException.class)
    public AppResponse handleBizException(BizException e){
        logger.error(e.getMessage(),e);
        String code = e.getCode();
        if(StringUtils.isBlank(code)){
            return AppResponse.error("空指针异常");
        }
        if(code.equals(AppResponseCode.CODE_ERROR_TOKEN.getCode())){
            AppResponse response = new AppResponse(AppResponseCode.CODE_ERROR_TOKEN.getCode());
            return response;
        }
        if(code.equals(AppResponseCode.CODE_ERROR_PARAM.getCode())){
            AppResponse response = new AppResponse(AppResponseCode.CODE_ERROR_PARAM.getCode());
            return response;
        }
        if(code.equals(AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getCode())){
            AppResponse response = new AppResponse(AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getCode());
            return response;
        }
        return AppResponse.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AppResponse handleException(Exception e){
        logger.error(e.getMessage(), e);
        if(e instanceof NullPointerException){
            return AppResponse.error("空指针异常");
        }
        return AppResponse.error(e.getMessage());
    }
}
